#include <16f877a.h>
#fuses xt,nowdt,nobrownout
#use delay (clock=4000000)
#include <lcd.c>
//#include "kbd_lib.c"

char k;
char const KEYS[4][4] = {{'1','2','3','F'},
                         {'4','5','6','E'},
                         {'7','8','9','D'},
                         {'A','0','B','C'}};

#byte kbd_port_b = 6

char kbd_getc(){
char tecla=0;
int f,c,t,i,j;
port_b_pullups(true);
set_tris_b(0b00001111); // RB7-RB4 salidas, RB3-RB0 entradas
for(f=0x10, i=0; i<4; f<<=1, i++){
    for(c=0x01, j=0; j<4; c<<=1, j++){
      kbd_port_b = ~f;
      delay_cycles(1);
      t = kbd_port_b & 0x0F;
      t = ~(t | 0xF0);
      if(t == c){
        delay_ms(20);
        tecla=KEYS[i][j];
        while(t==c){
          restart_wdt();
          t = kbd_port_b & 0x0F;
          t = ~(t | 0xF0);
        }
        break;
      }
    }
    if(tecla)
      break;
  }

  port_b_pullups(false);
  return tecla;
}

void main (void)
   {

   lcd_init(); // inicializar la libreria de trabajo para este caso lcd

   while(true)
      {
      k=kbd_getc();

      if(k==0){}
      else if(k=='1'){ lcd_putc(k);}
      else if(k=='2'){ lcd_putc(k);}
      else if(k=='3'){ lcd_putc(k);}
      else if(k=='4'){ lcd_putc(k);}
      else if(k=='5'){ lcd_putc(k);}
      else if(k=='6'){ lcd_putc(k);}
      else if(k=='7'){ lcd_putc(k);}
      else if(k=='8'){ lcd_putc(k);}
      else if(k=='9'){ lcd_putc(k);}
      else if(k=='0'){ lcd_putc(k);}
      else if(k=='A'){ lcd_putc("\n");}
      else if(k=='B'){ lcd_putc("\f");}

      }

   }
